org.springframework.data.document.mongodb
Class MongoTemplate

java.lang.Object
  extended by org.springframework.data.document.mongodb.MongoTemplate
All Implemented Interfaces:
MongoOperations

public class MongoTemplate
extends java.lang.Object
implements MongoOperations

Primary implementation of MongoOperations.

Author:
Thomas Risberg, Graeme Rocher, Mark Pollack, Oliver Gierke

Nested Class Summary
private static interface MongoTemplate.DbObjectCallback<T>
          Simple internal callback to allow operations on a DBObject.
private static class MongoTemplate.FindAndRemoveCallback
          Simple CollectionCallback that takes a query DBObject plus an optional fields specification DBObject and executes that against the DBCollection.
private static class MongoTemplate.FindCallback
          Simple CollectionCallback that takes a query DBObject plus an optional fields specification DBObject and executes that against the DBCollection.
private static class MongoTemplate.FindOneCallback
          Simple CollectionCallback that takes a query DBObject plus an optional fields specification DBObject and executes that against the DBCollection.
private  class MongoTemplate.ReadDbObjectCallback<T>
          Simple MongoTemplate.DbObjectCallback that will transform DBObject into the given target type using the given MongoReader.
 
Field Summary
private  ApplicationEventPublisher eventPublisher
           
private  MongoExceptionTranslator exceptionTranslator
           
private static java.lang.String ID
           
private  MongoPersistentEntityIndexCreator indexCreator
           
private static Log LOGGER
           
private  QueryMapper mapper
           
private   mappingContext
           
private  MongoConverter mongoConverter
           
private  MongoDbFactory mongoDbFactory
           
private  boolean slaveOk
           
private  WriteConcern writeConcern
           
private  WriteResultChecking writeResultChecking
           
 
Constructor Summary
MongoTemplate(MongoDbFactory mongoDbFactory)
          Constructor used for a basic template configuration
MongoTemplate(MongoDbFactory mongoDbFactory, MongoConverter mongoConverter)
          Constructor used for a basic template configuration
MongoTemplate(MongoDbFactory mongoDbFactory, MongoConverter mongoConverter, WriteConcern writeConcern, WriteResultChecking writeResultChecking)
          Constructor used for a template configuration with a custom MongoConverter and with a specific com.mongodb.WriteConcern to be used for all database write operations
MongoTemplate(Mongo mongo, java.lang.String databaseName)
          Constructor used for a basic template configuration
MongoTemplate(Mongo mongo, java.lang.String databaseName, UserCredentials userCredentials)
          Constructor used for a template configuration with user credentials in the form of org.springframework.data.authentication.UserCredentials
 
Method Summary
 boolean collectionExists(java.lang.String collectionName)
          Check to see if a collection with a given name exists.
private  ObjectId convertIdValue(MongoConverter converter, java.lang.Object value)
           
protected  DBObject convertToDbObject(CollectionOptions collectionOptions)
           
 DBCollection createCollection(java.lang.String collectionName)
          Create an uncapped collection with the provided name.
 DBCollection createCollection(java.lang.String collectionName, CollectionOptions collectionOptions)
          Create a collect with the provided name and options.
private  java.lang.String determineCollectionName(java.lang.Class<?> clazz)
           
private
<T> java.lang.String
determineEntityCollectionName(T obj)
           
protected  DBCollection doCreateCollection(java.lang.String collectionName, DBObject collectionOptions)
          Create the specified collection using the provided options
protected
<T> java.util.List<T>
doFind(java.lang.String collectionName, DBObject query, DBObject fields, java.lang.Class<T> targetClass)
          Map the results of an ad-hoc query on the default MongoDB collection to a List using the template's converter.
protected
<T> java.util.List<T>
doFind(java.lang.String collectionName, DBObject query, DBObject fields, java.lang.Class<T> targetClass, CursorPreparer preparer)
          Map the results of an ad-hoc query on the default MongoDB collection to a List of the specified type.
protected
<T> T
doFindAndRemove(java.lang.String collectionName, DBObject query, DBObject fields, DBObject sort, java.lang.Class<T> targetClass)
          Map the results of an ad-hoc query on the default MongoDB collection to an object using the template's converter.
protected
<T> T
doFindOne(java.lang.String collectionName, DBObject query, DBObject fields, java.lang.Class<T> targetClass)
          Map the results of an ad-hoc query on the default MongoDB collection to an object using the template's converter

The query document is specified as a standard DBObject and so is the fields specification.

protected
<T> void
doInsert(java.lang.String collectionName, T objectToSave, MongoWriter<T> writer)
           
protected
<T> void
doInsertList(java.util.List<? extends T> listToSave, MongoWriter<T> writer)
           
protected
<T> void
doInsertList(java.lang.String collectionName, java.util.List<? extends T> listToSave, MongoWriter<T> writer)
           
protected
<T> void
doSave(java.lang.String collectionName, T objectToSave, MongoWriter<T> writer)
           
protected  WriteResult doUpdate(java.lang.String collectionName, Query query, Update update, java.lang.Class<?> entityClass, boolean upsert, boolean multi)
           
 void dropCollection(java.lang.String collectionName)
          Drop the collection with the given name.
 void ensureIndex(java.lang.Class<?> entityClass, IndexDefinition indexDefinition)
          Ensure that an index for the provided IndexDefinition exists for the default collection.
 void ensureIndex(java.lang.String collectionName, IndexDefinition indexDefinition)
          Ensure that an index for the provided IndexDefinition exists.
<T> T
execute(java.lang.Class<?> entityClass, CollectionCallback<T> callback)
          Executes the given CollectionCallback on the entity collection of the specified class.
<T> T
execute(DbCallback<T> action)
          Executes a DbCallback translating any exceptions as necessary.
<T> T
execute(java.lang.String collectionName, CollectionCallback<T> callback)
          Executes the given CollectionCallback on the collection of the given name.
 CommandResult executeCommand(DBObject command)
          Execute the a MongoDB command expressed as a JSON string.
 CommandResult executeCommand(java.lang.String jsonCommand)
          Execute the a MongoDB command expressed as a JSON string.
private
<T> java.util.List<T>
executeFindMultiInternal(CollectionCallback<DBCursor> collectionCallback, CursorPreparer preparer, MongoTemplate.DbObjectCallback<T> objectCallback, java.lang.String collectionName)
          Internal method using callback to do queries against the datastore that requires reading a collection of objects.
private
<T> T
executeFindOneInternal(CollectionCallback<DBObject> collectionCallback, MongoTemplate.DbObjectCallback<T> objectCallback, java.lang.String collectionName)
          Internal method using callbacks to do queries against the datastore that requires reading a single object from a collection of objects.
<T> T
executeInSession(DbCallback<T> action)
          Executes the given DbCallback within the same connection to the database so as to ensure consistency in a write heavy environment where you may read the data that you wrote.
<T> java.util.List<T>
find(Query query, java.lang.Class<T> targetClass)
          Map the results of an ad-hoc query on the default MongoDB collection to a List of the specified type.
<T> java.util.List<T>
find(java.lang.String collectionName, Query query, java.lang.Class<T> targetClass)
          Map the results of an ad-hoc query on the specified collection to a List of the specified type.
<T> java.util.List<T>
find(java.lang.String collectionName, Query query, java.lang.Class<T> targetClass, CursorPreparer preparer)
          Map the results of an ad-hoc query on the specified collection to a List of the specified type.
<T> T
findAndRemove(Query query, java.lang.Class<T> targetClass)
          Map the results of an ad-hoc query on the default MongoDB collection to a single instance of an object of the specified type.
<T> T
findAndRemove(java.lang.String collectionName, Query query, java.lang.Class<T> targetClass)
          Map the results of an ad-hoc query on the specified collection to a single instance of an object of the specified type.
<T> T
findById(java.lang.Object id, java.lang.Class<T> targetClass)
          Returns a document with the given id mapped onto the given class.
<T> T
findById(java.lang.String collectionName, java.lang.Object id, java.lang.Class<T> targetClass)
          Returns the document with the given id from the given collection mapped onto the given target class.
<T> T
findOne(Query query, java.lang.Class<T> targetClass)
          Map the results of an ad-hoc query on the default MongoDB collection to a single instance of an object of the specified type.
<T> T
findOne(java.lang.String collectionName, Query query, java.lang.Class<T> targetClass)
          Map the results of an ad-hoc query on the specified collection to a single instance of an object of the specified type.
private  DBCollection getAndPrepareCollection(DB db, java.lang.String collectionName)
           
<T> java.util.List<T>
getCollection(java.lang.Class<T> targetClass)
          Query for a list of objects of type T from the default collection.
 DBCollection getCollection(java.lang.String collectionName)
          Get a collection by name, creating it if it doesn't exist.
<T> java.util.List<T>
getCollection(java.lang.String collectionName, java.lang.Class<T> targetClass)
          Query for a list of objects of type T from the specified collection.
 java.lang.String getCollectionName(java.lang.Class<?> clazz)
          The collection name used for the specified class by this template.
 java.util.Set<java.lang.String> getCollectionNames()
          A set of collection names.
 MongoConverter getConverter()
          Returns the default MongoConverter.
 DB getDb()
           
 MongoDbFactory getDbFactory()
          Returns the MongoDbFactory.
private  MongoConverter getDefaultMongoConverter()
           
private  MongoPersistentProperty getIdPropertyFor(java.lang.Class<?> type)
           
protected  java.lang.String getIdPropertyName(java.lang.Object object)
           
protected  java.lang.Object getIdValue(java.lang.Object object)
           
  getMappingContext()
           
private  MongoPersistentEntity<?> getPersistentEntity(java.lang.Class<?> type)
           
private  void handleAnyWriteResultErrors(WriteResult wr, DBObject query, java.lang.String operation)
          Checks and handles any errors.
 void insert(java.lang.Object objectToSave)
          Insert the object into the default collection.
 void insert(java.lang.String collectionName, java.lang.Object objectToSave)
          Insert the object into the specified collection.
protected  java.lang.Object insertDBObject(java.lang.String collectionName, DBObject dbDoc)
           
protected  java.util.List<ObjectId> insertDBObjectList(java.lang.String collectionName, java.util.List<DBObject> dbDocList)
           
 void insertList(java.util.List<? extends java.lang.Object> listToSave)
          Insert a list of objects into the default collection in a single batch write to the database.
 void insertList(java.lang.String collectionName, java.util.List<? extends java.lang.Object> listToSave)
          Insert a list of objects into the specified collection in a single batch write to the database.
protected
<T> void
maybeEmitEvent(MongoMappingEvent<T> event)
           
protected  void populateIdIfNecessary(java.lang.Object savedObject, java.lang.Object id)
          Populates the id property of the saved object, if it's not set already.
private  java.lang.RuntimeException potentiallyConvertRuntimeException(java.lang.RuntimeException ex)
          Tries to convert the given RuntimeException into a DataAccessException but returns the original exception if the conversation failed.
protected  void prepareCollection(DBCollection collection)
          Prepare the collection before any processing is done using it.
protected  WriteConcern prepareWriteConcern(WriteConcern writeConcern)
          Prepare the WriteConcern before any processing is done using it.
 void remove(java.lang.Object object)
          Remove the given object from the collection by Id
 void remove(Query query)
          Remove all documents from the default collection that match the provided query document criteria.
<T> void
remove(Query query, java.lang.Class<T> targetClass)
          Remove all documents from the default collection that match the provided query document criteria.
 void remove(java.lang.String collectionName, Query query)
          Remove all documents from the specified collection that match the provided query document criteria.
<T> void
remove(java.lang.String collectionName, Query query, java.lang.Class<T> targetClass)
          Remove all documents from the specified collection that match the provided query document criteria.
 void save(java.lang.Object objectToSave)
          Save the object to the default collection.
 void save(java.lang.String collectionName, java.lang.Object objectToSave)
          Save the object to the specified collection.
protected  java.lang.Object saveDBObject(java.lang.String collectionName, DBObject dbDoc)
           
 void setApplicationContext(ApplicationContext applicationContext)
           
 void setSlaveOk(boolean slaveOk)
           
 void setWriteConcern(WriteConcern writeConcern)
           
 void setWriteResultChecking(WriteResultChecking resultChecking)
           
 WriteResult updateFirst(java.lang.Class<?> entityClass, Query query, Update update)
          Updates the first object that is found in the default collection that matches the query document with the provided updated document.
 WriteResult updateFirst(java.lang.String collectionName, Query query, Update update)
          Updates the first object that is found in the specified collection that matches the query document criteria with the provided updated document.
 WriteResult updateMulti(java.lang.Class<?> entityClass, Query query, Update update)
          Updates all objects that are found in the default collection that matches the query document criteria with the provided updated document.
 WriteResult updateMulti(java.lang.String collectionName, Query query, Update update)
          Updates all objects that are found in the specified collection that matches the query document criteria with the provided updated document.
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Field Detail

LOGGER

private static final Log LOGGER

ID

private static final java.lang.String ID
See Also:
Constant Field Values

writeConcern

private WriteConcern writeConcern

writeResultChecking

private WriteResultChecking writeResultChecking

slaveOk

private boolean slaveOk

mongoConverter

private MongoConverter mongoConverter

mappingContext

private  mappingContext

mongoDbFactory

private MongoDbFactory mongoDbFactory

exceptionTranslator

private MongoExceptionTranslator exceptionTranslator

mapper

private QueryMapper mapper

eventPublisher

private ApplicationEventPublisher eventPublisher

indexCreator

private MongoPersistentEntityIndexCreator indexCreator
Constructor Detail

MongoTemplate

public MongoTemplate(Mongo mongo,
                     java.lang.String databaseName)
Constructor used for a basic template configuration

Parameters:
mongo -
databaseName -

MongoTemplate

public MongoTemplate(Mongo mongo,
                     java.lang.String databaseName,
                     UserCredentials userCredentials)
Constructor used for a template configuration with user credentials in the form of org.springframework.data.authentication.UserCredentials

Parameters:
mongo -
databaseName -
userCredentials -

MongoTemplate

public MongoTemplate(MongoDbFactory mongoDbFactory)
Constructor used for a basic template configuration

Parameters:
mongoDbFactory -

MongoTemplate

public MongoTemplate(MongoDbFactory mongoDbFactory,
                     MongoConverter mongoConverter)
Constructor used for a basic template configuration

Parameters:
mongoDbFactory -
mongoConverter -

MongoTemplate

MongoTemplate(MongoDbFactory mongoDbFactory,
              MongoConverter mongoConverter,
              WriteConcern writeConcern,
              WriteResultChecking writeResultChecking)
Constructor used for a template configuration with a custom MongoConverter and with a specific com.mongodb.WriteConcern to be used for all database write operations

Parameters:
mongoDbFactory -
mongoConverter -
writeConcern -
writeResultChecking -
Method Detail

getDefaultMongoConverter

private final MongoConverter getDefaultMongoConverter()

setApplicationContext

public void setApplicationContext(ApplicationContext applicationContext)
                           throws BeansException
Throws:
BeansException

getConverter

public MongoConverter getConverter()
Returns the default MongoConverter.

Returns:

getDbFactory

public MongoDbFactory getDbFactory()
Returns the MongoDbFactory.

Returns:

getMappingContext

public  getMappingContext()

getCollectionName

public java.lang.String getCollectionName(java.lang.Class<?> clazz)
Description copied from interface: MongoOperations
The collection name used for the specified class by this template.

Specified by:
getCollectionName in interface MongoOperations
Returns:

executeCommand

public CommandResult executeCommand(java.lang.String jsonCommand)
Description copied from interface: MongoOperations
Execute the a MongoDB command expressed as a JSON string. This will call the method JSON.parse that is part of the MongoDB driver to convert the JSON string to a DBObject. Any errors that result from executing this command will be converted into Spring's DAO exception hierarchy.

Specified by:
executeCommand in interface MongoOperations
Parameters:
jsonCommand - a MongoDB command expressed as a JSON string.

executeCommand

public CommandResult executeCommand(DBObject command)
Description copied from interface: MongoOperations
Execute the a MongoDB command expressed as a JSON string. This will call the method JSON.parse that is part of the MongoDB driver to convert the JSON string to a DBObject. Any errors that result from executing this command will be converted into Spring's DAO exception hierarchy.

Specified by:
executeCommand in interface MongoOperations
Parameters:
command - a MongoDB command expressed as a JSON string.

execute

public <T> T execute(DbCallback<T> action)
Description copied from interface: MongoOperations
Executes a DbCallback translating any exceptions as necessary.

Allows for returning a result object, that is a domain object or a collection of domain objects.

Specified by:
execute in interface MongoOperations
Type Parameters:
T - return type
Parameters:
action - callback object that specifies the MongoDB actions to perform on the passed in DB instance.
Returns:
a result object returned by the action or null

execute

public <T> T execute(java.lang.Class<?> entityClass,
                     CollectionCallback<T> callback)
Description copied from interface: MongoOperations
Executes the given CollectionCallback on the entity collection of the specified class.

Allows for returning a result object, that is a domain object or a collection of domain objects.

Specified by:
execute in interface MongoOperations
Type Parameters:
T - return type
Parameters:
entityClass - class that determines the collection to use
callback - callback object that specifies the MongoDB action
Returns:
a result object returned by the action or null

execute

public <T> T execute(java.lang.String collectionName,
                     CollectionCallback<T> callback)
Description copied from interface: MongoOperations
Executes the given CollectionCallback on the collection of the given name.

Allows for returning a result object, that is a domain object or a collection of domain objects.

Specified by:
execute in interface MongoOperations
Type Parameters:
T - return type
Parameters:
collectionName - the name of the collection that specifies which DBCollection instance will be passed into
callback - callback object that specifies the MongoDB action the callback action.
Returns:
a result object returned by the action or null

executeInSession

public <T> T executeInSession(DbCallback<T> action)
Description copied from interface: MongoOperations
Executes the given DbCallback within the same connection to the database so as to ensure consistency in a write heavy environment where you may read the data that you wrote. See the comments on Java Driver Concurrency

Allows for returning a result object, that is a domain object or a collection of domain objects.

Specified by:
executeInSession in interface MongoOperations
Type Parameters:
T - return type
Parameters:
action - callback that specified the MongoDB actions to perform on the DB instance
Returns:
a result object returned by the action or null

createCollection

public DBCollection createCollection(java.lang.String collectionName)
Description copied from interface: MongoOperations
Create an uncapped collection with the provided name.

Specified by:
createCollection in interface MongoOperations
Parameters:
collectionName - name of the collection
Returns:
the created collection

createCollection

public DBCollection createCollection(java.lang.String collectionName,
                                     CollectionOptions collectionOptions)
Description copied from interface: MongoOperations
Create a collect with the provided name and options.

Specified by:
createCollection in interface MongoOperations
Parameters:
collectionName - name of the collection
collectionOptions - options to use when creating the collection.
Returns:
the created collection

getCollection

public DBCollection getCollection(java.lang.String collectionName)
Description copied from interface: MongoOperations
Get a collection by name, creating it if it doesn't exist.

Translate any exceptions as necessary.

Specified by:
getCollection in interface MongoOperations
Parameters:
collectionName - name of the collection
Returns:
an existing collection or a newly created one.

collectionExists

public boolean collectionExists(java.lang.String collectionName)
Description copied from interface: MongoOperations
Check to see if a collection with a given name exists.

Translate any exceptions as necessary.

Specified by:
collectionExists in interface MongoOperations
Parameters:
collectionName - name of the collection
Returns:
true if a collection with the given name is found, false otherwise.

dropCollection

public void dropCollection(java.lang.String collectionName)
Description copied from interface: MongoOperations
Drop the collection with the given name.

Translate any exceptions as necessary.

Specified by:
dropCollection in interface MongoOperations
Parameters:
collectionName - name of the collection to drop/delete.

ensureIndex

public void ensureIndex(java.lang.Class<?> entityClass,
                        IndexDefinition indexDefinition)
Description copied from interface: MongoOperations
Ensure that an index for the provided IndexDefinition exists for the default collection. If not it will be created.

Specified by:
ensureIndex in interface MongoOperations
Parameters:
entityClass - class that determines the collection to use

ensureIndex

public void ensureIndex(java.lang.String collectionName,
                        IndexDefinition indexDefinition)
Description copied from interface: MongoOperations
Ensure that an index for the provided IndexDefinition exists. If not it will be created.

Specified by:
ensureIndex in interface MongoOperations

findOne

public <T> T findOne(Query query,
                     java.lang.Class<T> targetClass)
Description copied from interface: MongoOperations
Map the results of an ad-hoc query on the default MongoDB collection to a single instance of an object of the specified type.

The object is converted from the MongoDB native representation using an instance of MongoConverter. Unless configured otherwise, an instance of SimpleMongoConverter will be used.

The query is specified as a Query which can be created either using the BasicQuery or the more feature rich Query.

Specified by:
findOne in interface MongoOperations
Parameters:
query - the query class that specifies the criteria used to find a record and also an optional fields specification
targetClass - the parameterized type of the returned list.
Returns:
the converted object

findOne

public <T> T findOne(java.lang.String collectionName,
                     Query query,
                     java.lang.Class<T> targetClass)
Description copied from interface: MongoOperations
Map the results of an ad-hoc query on the specified collection to a single instance of an object of the specified type.

The object is converted from the MongoDB native representation using an instance of MongoConverter. Unless configured otherwise, an instance of SimpleMongoConverter will be used.

The query is specified as a Query which can be created either using the BasicQuery or the more feature rich Query.

Specified by:
findOne in interface MongoOperations
Parameters:
collectionName - name of the collection to retrieve the objects from
query - the query class that specifies the criteria used to find a record and also an optional fields specification
targetClass - the parameterized type of the returned list.
Returns:
the converted object

find

public <T> java.util.List<T> find(Query query,
                                  java.lang.Class<T> targetClass)
Description copied from interface: MongoOperations
Map the results of an ad-hoc query on the default MongoDB collection to a List of the specified type.

The object is converted from the MongoDB native representation using an instance of MongoConverter. Unless configured otherwise, an instance of SimpleMongoConverter will be used.

The query is specified as a Query which can be created either using the BasicQuery or the more feature rich Query.

Specified by:
find in interface MongoOperations
Parameters:
query - the query class that specifies the criteria used to find a record and also an optional fields specification
targetClass - the parameterized type of the returned list.
Returns:
the List of converted objects

find

public <T> java.util.List<T> find(java.lang.String collectionName,
                                  Query query,
                                  java.lang.Class<T> targetClass)
Description copied from interface: MongoOperations
Map the results of an ad-hoc query on the specified collection to a List of the specified type.

The object is converted from the MongoDB native representation using an instance of MongoConverter. Unless configured otherwise, an instance of SimpleMongoConverter will be used.

The query is specified as a Query which can be created either using the BasicQuery or the more feature rich Query.

Specified by:
find in interface MongoOperations
Parameters:
collectionName - name of the collection to retrieve the objects from
query - the query class that specifies the criteria used to find a record and also an optional fields specification
targetClass - the parameterized type of the returned list.
Returns:
the List of converted objects

find

public <T> java.util.List<T> find(java.lang.String collectionName,
                                  Query query,
                                  java.lang.Class<T> targetClass,
                                  CursorPreparer preparer)
Description copied from interface: MongoOperations
Map the results of an ad-hoc query on the specified collection to a List of the specified type.

The object is converted from the MongoDB native representation using an instance of MongoConverter. Unless configured otherwise, an instance of SimpleMongoConverter will be used.

The query is specified as a Query which can be created either using the BasicQuery or the more feature rich Query.

Specified by:
find in interface MongoOperations
Parameters:
collectionName - name of the collection to retrieve the objects from
query - the query class that specifies the criteria used to find a record and also an optional fields specification
targetClass - the parameterized type of the returned list.
preparer - allows for customization of the DBCursor used when iterating over the result set, (apply limits, skips and so on).
Returns:
the List of converted objects.

findById

public <T> T findById(java.lang.Object id,
                      java.lang.Class<T> targetClass)
Description copied from interface: MongoOperations
Returns a document with the given id mapped onto the given class. The collection the query is ran against will be derived from the given target class as well.

Specified by:
findById in interface MongoOperations
Parameters:
id - the id of the document to return.
targetClass - the type the document shall be converted into.
Returns:
the document with the given id mapped onto the given target class.

findById

public <T> T findById(java.lang.String collectionName,
                      java.lang.Object id,
                      java.lang.Class<T> targetClass)
Description copied from interface: MongoOperations
Returns the document with the given id from the given collection mapped onto the given target class.

Specified by:
findById in interface MongoOperations
Parameters:
collectionName - the collection to query for the document
id - the id of the document to return
targetClass - the type to convert the document to
Returns:

findAndRemove

public <T> T findAndRemove(Query query,
                           java.lang.Class<T> targetClass)
Description copied from interface: MongoOperations
Map the results of an ad-hoc query on the default MongoDB collection to a single instance of an object of the specified type. The first document that matches the query is returned and also removed from the collection in the database.

The object is converted from the MongoDB native representation using an instance of MongoConverter. Unless configured otherwise, an instance of SimpleMongoConverter will be used.

The query is specified as a Query which can be created either using the BasicQuery or the more feature rich Query.

Specified by:
findAndRemove in interface MongoOperations
Parameters:
query - the query class that specifies the criteria used to find a record and also an optional fields specification
targetClass - the parameterized type of the returned list.
Returns:
the converted object

findAndRemove

public <T> T findAndRemove(java.lang.String collectionName,
                           Query query,
                           java.lang.Class<T> targetClass)
Description copied from interface: MongoOperations
Map the results of an ad-hoc query on the specified collection to a single instance of an object of the specified type. The first document that matches the query is returned and also removed from the collection in the database.

The object is converted from the MongoDB native representation using an instance of MongoConverter. Unless configured otherwise, an instance of SimpleMongoConverter will be used.

The query is specified as a Query which can be created either using the BasicQuery or the more feature rich Query.

Specified by:
findAndRemove in interface MongoOperations
Parameters:
collectionName - name of the collection to retrieve the objects from
query - the query class that specifies the criteria used to find a record and also an optional fields specification
targetClass - the parameterized type of the returned list.
Returns:
the converted object

insert

public void insert(java.lang.Object objectToSave)
Description copied from interface: MongoOperations
Insert the object into the default collection.

The object is converted to the MongoDB native representation using an instance of MongoConverter. Unless configured otherwise, an instance of SimpleMongoConverter will be used.

If you object has an "Id' property, it will be set with the generated Id from MongoDB. If your Id property is a String then MongoDB ObjectId will be used to populate that string. Otherwise, the conversion from ObjectId to your property type will be handled by Spring's BeanWrapper class that leverages Spring 3.0's new Type Conversion API. See Spring 3 Type Conversion" for more details.

Insert is used to initially store the object into the database. To update an existing object use the save method.

Specified by:
insert in interface MongoOperations
Parameters:
objectToSave - the object to store in the collection.

insert

public void insert(java.lang.String collectionName,
                   java.lang.Object objectToSave)
Description copied from interface: MongoOperations
Insert the object into the specified collection.

The object is converted to the MongoDB native representation using an instance of MongoConverter. Unless configured otherwise, an instance of SimpleMongoConverter will be used.

Insert is used to initially store the object into the database. To update an existing object use the save method.

Specified by:
insert in interface MongoOperations
Parameters:
collectionName - name of the collection to store the object in
objectToSave - the object to store in the collection

prepareCollection

protected void prepareCollection(DBCollection collection)
Prepare the collection before any processing is done using it. This allows a convenient way to apply settings like slaveOk() etc. Can be overridden in sub-classes.

Parameters:
collection -

prepareWriteConcern

protected WriteConcern prepareWriteConcern(WriteConcern writeConcern)
Prepare the WriteConcern before any processing is done using it. This allows a convenient way to apply custom settings in sub-classes.

Parameters:
writeConcern - any WriteConcern already configured or null
Returns:
The prepared WriteConcern or null

doInsert

protected <T> void doInsert(java.lang.String collectionName,
                            T objectToSave,
                            MongoWriter<T> writer)

insertList

public void insertList(java.util.List<? extends java.lang.Object> listToSave)
Description copied from interface: MongoOperations
Insert a list of objects into the default collection in a single batch write to the database.

Specified by:
insertList in interface MongoOperations
Parameters:
listToSave - the list of objects to save.

insertList

public void insertList(java.lang.String collectionName,
                       java.util.List<? extends java.lang.Object> listToSave)
Description copied from interface: MongoOperations
Insert a list of objects into the specified collection in a single batch write to the database.

Specified by:
insertList in interface MongoOperations
Parameters:
collectionName - name of the collection to store the object in
listToSave - the list of objects to save.

doInsertList

protected <T> void doInsertList(java.util.List<? extends T> listToSave,
                                MongoWriter<T> writer)

doInsertList

protected <T> void doInsertList(java.lang.String collectionName,
                                java.util.List<? extends T> listToSave,
                                MongoWriter<T> writer)

save

public void save(java.lang.Object objectToSave)
Description copied from interface: MongoOperations
Save the object to the default collection. This will perform an insert if the object is not already present, that is an 'upsert'.

The object is converted to the MongoDB native representation using an instance of MongoConverter. Unless configured otherwise, an instance of SimpleMongoConverter will be used.

If you object has an "Id' property, it will be set with the generated Id from MongoDB. If your Id property is a String then MongoDB ObjectId will be used to populate that string. Otherwise, the conversion from ObjectId to your property type will be handled by Spring's BeanWrapper class that leverages Spring 3.0's new Type Conversion API. See Spring 3 Type Conversion" for more details.

Specified by:
save in interface MongoOperations
Parameters:
objectToSave - the object to store in the collection

save

public void save(java.lang.String collectionName,
                 java.lang.Object objectToSave)
Description copied from interface: MongoOperations
Save the object to the specified collection. This will perform an insert if the object is not already present, that is an 'upsert'.

The object is converted to the MongoDB native representation using an instance of MongoConverter. Unless configured otherwise, an instance of SimpleMongoConverter will be used.

If you object has an "Id' property, it will be set with the generated Id from MongoDB. If your Id property is a String then MongoDB ObjectId will be used to populate that string. Otherwise, the conversion from ObjectId to your property type will be handled by Spring's BeanWrapper class that leverages Spring 3.0's new Type Cobnversion API. See Spring 3 Type Conversion" for more details.

Specified by:
save in interface MongoOperations
Parameters:
collectionName - name of the collection to store the object in
objectToSave - the object to store in the collection

doSave

protected <T> void doSave(java.lang.String collectionName,
                          T objectToSave,
                          MongoWriter<T> writer)

insertDBObject

protected java.lang.Object insertDBObject(java.lang.String collectionName,
                                          DBObject dbDoc)

insertDBObjectList

protected java.util.List<ObjectId> insertDBObjectList(java.lang.String collectionName,
                                                      java.util.List<DBObject> dbDocList)

saveDBObject

protected java.lang.Object saveDBObject(java.lang.String collectionName,
                                        DBObject dbDoc)

updateFirst

public WriteResult updateFirst(java.lang.Class<?> entityClass,
                               Query query,
                               Update update)
Description copied from interface: MongoOperations
Updates the first object that is found in the default collection that matches the query document with the provided updated document.

Specified by:
updateFirst in interface MongoOperations
Parameters:
entityClass - class that determines the collection to use

updateFirst

public WriteResult updateFirst(java.lang.String collectionName,
                               Query query,
                               Update update)
Description copied from interface: MongoOperations
Updates the first object that is found in the specified collection that matches the query document criteria with the provided updated document.

Specified by:
updateFirst in interface MongoOperations
Parameters:
collectionName - name of the collection to update the object in

updateMulti

public WriteResult updateMulti(java.lang.Class<?> entityClass,
                               Query query,
                               Update update)
Description copied from interface: MongoOperations
Updates all objects that are found in the default collection that matches the query document criteria with the provided updated document.

Specified by:
updateMulti in interface MongoOperations
Parameters:
entityClass - class that determines the collection to use

updateMulti

public WriteResult updateMulti(java.lang.String collectionName,
                               Query query,
                               Update update)
Description copied from interface: MongoOperations
Updates all objects that are found in the specified collection that matches the query document criteria with the provided updated document.

Specified by:
updateMulti in interface MongoOperations
Parameters:
collectionName - name of the collection to update the object in

doUpdate

protected WriteResult doUpdate(java.lang.String collectionName,
                               Query query,
                               Update update,
                               java.lang.Class<?> entityClass,
                               boolean upsert,
                               boolean multi)

remove

public void remove(Query query)
Description copied from interface: MongoOperations
Remove all documents from the default collection that match the provided query document criteria.

Specified by:
remove in interface MongoOperations

remove

public void remove(java.lang.Object object)
Description copied from interface: MongoOperations
Remove the given object from the collection by Id

Specified by:
remove in interface MongoOperations

remove

public <T> void remove(Query query,
                       java.lang.Class<T> targetClass)
Description copied from interface: MongoOperations
Remove all documents from the default collection that match the provided query document criteria. The Class parameter is used to help convert the Id of the object if it is present in the query.

Specified by:
remove in interface MongoOperations

remove

public <T> void remove(java.lang.String collectionName,
                       Query query,
                       java.lang.Class<T> targetClass)
Description copied from interface: MongoOperations
Remove all documents from the specified collection that match the provided query document criteria. The Class parameter is used to help convert the Id of the object if it is present in the query.

Specified by:
remove in interface MongoOperations

remove

public void remove(java.lang.String collectionName,
                   Query query)
Description copied from interface: MongoOperations
Remove all documents from the specified collection that match the provided query document criteria.

Specified by:
remove in interface MongoOperations
Parameters:
collectionName - name of the collection where the objects will removed

getCollection

public <T> java.util.List<T> getCollection(java.lang.Class<T> targetClass)
Description copied from interface: MongoOperations
Query for a list of objects of type T from the default collection.

The object is converted from the MongoDB native representation using an instance of MongoConverter. Unless configured otherwise, an instance of SimpleMongoConverter will be used.

If your collection does not contain a homogeneous collection of types, this operation will not be an efficient way to map objects since the test for class type is done in the client and not on the server.

Specified by:
getCollection in interface MongoOperations
Parameters:
targetClass - the parameterized type of the returned list
Returns:
the converted collection

getCollection

public <T> java.util.List<T> getCollection(java.lang.String collectionName,
                                           java.lang.Class<T> targetClass)
Description copied from interface: MongoOperations
Query for a list of objects of type T from the specified collection.

The object is converted from the MongoDB native representation using an instance of MongoConverter. Unless configured otherwise, an instance of SimpleMongoConverter will be used.

If your collection does not contain a homogeneous collection of types, this operation will not be an efficient way to map objects since the test for class type is done in the client and not on the server.

Specified by:
getCollection in interface MongoOperations
Parameters:
collectionName - name of the collection to retrieve the objects from
targetClass - the parameterized type of the returned list.
Returns:
the converted collection

getCollectionNames

public java.util.Set<java.lang.String> getCollectionNames()
Description copied from interface: MongoOperations
A set of collection names.

Specified by:
getCollectionNames in interface MongoOperations
Returns:
list of collection names

getDb

public DB getDb()

maybeEmitEvent

protected <T> void maybeEmitEvent(MongoMappingEvent<T> event)

doCreateCollection

protected DBCollection doCreateCollection(java.lang.String collectionName,
                                          DBObject collectionOptions)
Create the specified collection using the provided options

Parameters:
collectionName -
collectionOptions -
Returns:
the collection that was created

doFindOne

protected <T> T doFindOne(java.lang.String collectionName,
                          DBObject query,
                          DBObject fields,
                          java.lang.Class<T> targetClass)
Map the results of an ad-hoc query on the default MongoDB collection to an object using the template's converter

The query document is specified as a standard DBObject and so is the fields specification.

Parameters:
collectionName - name of the collection to retrieve the objects from
query - the query document that specifies the criteria used to find a record
fields - the document that specifies the fields to be returned
targetClass - the parameterized type of the returned list.
Returns:
the List of converted objects.

doFind

protected <T> java.util.List<T> doFind(java.lang.String collectionName,
                                       DBObject query,
                                       DBObject fields,
                                       java.lang.Class<T> targetClass,
                                       CursorPreparer preparer)
Map the results of an ad-hoc query on the default MongoDB collection to a List of the specified type.

The object is converted from the MongoDB native representation using an instance of MongoConverter. Unless configured otherwise, an instance of SimpleMongoConverter will be used.

The query document is specified as a standard DBObject and so is the fields specification.

Can be overridden by subclasses.

Parameters:
collectionName - name of the collection to retrieve the objects from
query - the query document that specifies the criteria used to find a record
fields - the document that specifies the fields to be returned
targetClass - the parameterized type of the returned list.
preparer - allows for customization of the DBCursor used when iterating over the result set, (apply limits, skips and so on).
Returns:
the List of converted objects.

doFind

protected <T> java.util.List<T> doFind(java.lang.String collectionName,
                                       DBObject query,
                                       DBObject fields,
                                       java.lang.Class<T> targetClass)
Map the results of an ad-hoc query on the default MongoDB collection to a List using the template's converter.

The query document is specified as a standard DBObject and so is the fields specification.

Parameters:
collectionName - name of the collection to retrieve the objects from
query - the query document that specifies the criteria used to find a record
fields - the document that specifies the fields to be returned
targetClass - the parameterized type of the returned list.
Returns:
the List of converted objects.

convertToDbObject

protected DBObject convertToDbObject(CollectionOptions collectionOptions)

doFindAndRemove

protected <T> T doFindAndRemove(java.lang.String collectionName,
                                DBObject query,
                                DBObject fields,
                                DBObject sort,
                                java.lang.Class<T> targetClass)
Map the results of an ad-hoc query on the default MongoDB collection to an object using the template's converter. The first document that matches the query is returned and also removed from the collection in the database.

The query document is specified as a standard DBObject and so is the fields specification.

Parameters:
collectionName - name of the collection to retrieve the objects from
query - the query document that specifies the criteria used to find a record
targetClass - the parameterized type of the returned list.
Returns:
the List of converted objects.

getIdValue

protected java.lang.Object getIdValue(java.lang.Object object)

getIdPropertyName

protected java.lang.String getIdPropertyName(java.lang.Object object)

populateIdIfNecessary

protected void populateIdIfNecessary(java.lang.Object savedObject,
                                     java.lang.Object id)
Populates the id property of the saved object, if it's not set already.

Parameters:
savedObject -
id -

getAndPrepareCollection

private DBCollection getAndPrepareCollection(DB db,
                                             java.lang.String collectionName)

executeFindOneInternal

private <T> T executeFindOneInternal(CollectionCallback<DBObject> collectionCallback,
                                     MongoTemplate.DbObjectCallback<T> objectCallback,
                                     java.lang.String collectionName)
Internal method using callbacks to do queries against the datastore that requires reading a single object from a collection of objects. It will take the following steps
  1. Execute the given ConnectionCallback for a DBObject.
  2. Apply the given MongoTemplate.DbObjectCallback to each of the DBObjects to obtain the result.
    1. Type Parameters:
      T -
      Parameters:
      collectionCallback - the callback to retrieve the DBObject with
      objectCallback - the MongoTemplate.DbObjectCallback to transform DBObjects into the actual domain type
      collectionName - the collection to be queried
      Returns:

executeFindMultiInternal

private <T> java.util.List<T> executeFindMultiInternal(CollectionCallback<DBCursor> collectionCallback,
                                                       CursorPreparer preparer,
                                                       MongoTemplate.DbObjectCallback<T> objectCallback,
                                                       java.lang.String collectionName)
Internal method using callback to do queries against the datastore that requires reading a collection of objects. It will take the following steps
  1. Execute the given ConnectionCallback for a DBCursor.
  2. Prepare that DBCursor with the given CursorPreparer (will be skipped if CursorPreparer is null
  3. Iterate over the DBCursor and applies the given MongoTemplate.DbObjectCallback to each of the DBObjects collecting the actual result List.
    1. Type Parameters:
      T -
      Parameters:
      collectionCallback - the callback to retrieve the DBCursor with
      preparer - the CursorPreparer to potentially modify the DBCursor before ireating over it
      objectCallback - the MongoTemplate.DbObjectCallback to transform DBObjects into the actual domain type
      collectionName - the collection to be queried
      Returns:

getPersistentEntity

private MongoPersistentEntity<?> getPersistentEntity(java.lang.Class<?> type)

getIdPropertyFor

private MongoPersistentProperty getIdPropertyFor(java.lang.Class<?> type)

convertIdValue

private ObjectId convertIdValue(MongoConverter converter,
                                java.lang.Object value)

determineEntityCollectionName

private <T> java.lang.String determineEntityCollectionName(T obj)

determineCollectionName

private java.lang.String determineCollectionName(java.lang.Class<?> clazz)

handleAnyWriteResultErrors

private void handleAnyWriteResultErrors(WriteResult wr,
                                        DBObject query,
                                        java.lang.String operation)
Checks and handles any errors.

TODO: current implementation logs errors - will be configurable to log warning, errors or throw exception in later versions


potentiallyConvertRuntimeException

private java.lang.RuntimeException potentiallyConvertRuntimeException(java.lang.RuntimeException ex)
Tries to convert the given RuntimeException into a DataAccessException but returns the original exception if the conversation failed. Thus allows safe rethrowing of the return value.

Parameters:
ex -
Returns:

setWriteResultChecking

public void setWriteResultChecking(WriteResultChecking resultChecking)

setWriteConcern

public void setWriteConcern(WriteConcern writeConcern)

setSlaveOk

public void setSlaveOk(boolean slaveOk)